route.ts 4.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176
  1. import { getServerSideConfig } from "@/app/config/server";
  2. import {
  3. BAIDU_BASE_URL,
  4. ApiPath,
  5. ModelProvider,
  6. BAIDU_OATUH_URL,
  7. ServiceProvider,
  8. } from "@/app/constant";
  9. import { prettyObject } from "@/app/utils/format";
  10. import { NextRequest, NextResponse } from "next/server";
  11. import { auth } from "@/app/api/auth";
  12. import { isModelAvailableInServer } from "@/app/utils/model";
  13. const serverConfig = getServerSideConfig();
  14. async function handle(
  15. req: NextRequest,
  16. { params }: { params: { path: string[] } },
  17. ) {
  18. console.log("[Baidu Route] params ", params);
  19. if (req.method === "OPTIONS") {
  20. return NextResponse.json({ body: "OK" }, { status: 200 });
  21. }
  22. const authResult = auth(req, ModelProvider.Ernie);
  23. if (authResult.error) {
  24. return NextResponse.json(authResult, {
  25. status: 401,
  26. });
  27. }
  28. try {
  29. const response = await request(req);
  30. return response;
  31. } catch (e) {
  32. console.error("[Baidu] ", e);
  33. return NextResponse.json(prettyObject(e));
  34. }
  35. }
  36. export const GET = handle;
  37. export const POST = handle;
  38. export const runtime = "edge";
  39. export const preferredRegion = [
  40. "arn1",
  41. "bom1",
  42. "cdg1",
  43. "cle1",
  44. "cpt1",
  45. "dub1",
  46. "fra1",
  47. "gru1",
  48. "hnd1",
  49. "iad1",
  50. "icn1",
  51. "kix1",
  52. "lhr1",
  53. "pdx1",
  54. "sfo1",
  55. "sin1",
  56. "syd1",
  57. ];
  58. async function request(req: NextRequest) {
  59. const controller = new AbortController();
  60. let path = `${req.nextUrl.pathname}`.replaceAll(ApiPath.Baidu, "");
  61. let baseUrl = serverConfig.baiduUrl || BAIDU_BASE_URL;
  62. if (!baseUrl.startsWith("http")) {
  63. baseUrl = `https://${baseUrl}`;
  64. }
  65. if (baseUrl.endsWith("/")) {
  66. baseUrl = baseUrl.slice(0, -1);
  67. }
  68. console.log("[Proxy] ", path);
  69. console.log("[Base Url]", baseUrl);
  70. const timeoutId = setTimeout(
  71. () => {
  72. controller.abort();
  73. },
  74. 10 * 60 * 1000,
  75. );
  76. const { access_token } = await getAccessToken();
  77. const fetchUrl = `${baseUrl}${path}?access_token=${access_token}`;
  78. const fetchOptions: RequestInit = {
  79. headers: {
  80. "Content-Type": "application/json",
  81. },
  82. method: req.method,
  83. body: req.body,
  84. redirect: "manual",
  85. // @ts-ignore
  86. duplex: "half",
  87. signal: controller.signal,
  88. };
  89. // #1815 try to refuse some request to some models
  90. if (serverConfig.customModels && req.body) {
  91. try {
  92. const clonedBody = await req.text();
  93. fetchOptions.body = clonedBody;
  94. const jsonBody = JSON.parse(clonedBody) as { model?: string };
  95. // not undefined and is false
  96. if (
  97. isModelAvailableInServer(
  98. serverConfig.customModels,
  99. jsonBody?.model as string,
  100. ServiceProvider.Baidu as string,
  101. )
  102. ) {
  103. return NextResponse.json(
  104. {
  105. error: true,
  106. message: `you are not allowed to use ${jsonBody?.model} model`,
  107. },
  108. {
  109. status: 403,
  110. },
  111. );
  112. }
  113. } catch (e) {
  114. console.error(`[Baidu] filter`, e);
  115. }
  116. }
  117. console.log("[Baidu request]", fetchOptions.headers, req.method);
  118. try {
  119. const res = await fetch(fetchUrl, fetchOptions);
  120. console.log("[Baidu response]", res.status, " ", res.headers, res.url);
  121. // to prevent browser prompt for credentials
  122. const newHeaders = new Headers(res.headers);
  123. newHeaders.delete("www-authenticate");
  124. // to disable nginx buffering
  125. newHeaders.set("X-Accel-Buffering", "no");
  126. return new Response(res.body, {
  127. status: res.status,
  128. statusText: res.statusText,
  129. headers: newHeaders,
  130. });
  131. } finally {
  132. clearTimeout(timeoutId);
  133. }
  134. }
  135. /**
  136. * 使用 AK,SK 生成鉴权签名(Access Token)
  137. * @return 鉴权签名信息
  138. */
  139. async function getAccessToken(): Promise<{
  140. access_token: string;
  141. expires_in: number;
  142. error?: number;
  143. }> {
  144. const AK = serverConfig.baiduApiKey;
  145. const SK = serverConfig.baiduSecretKey;
  146. const res = await fetch(
  147. `${BAIDU_OATUH_URL}?grant_type=client_credentials&client_id=${AK}&client_secret=${SK}`,
  148. {
  149. method: "POST",
  150. },
  151. );
  152. const resJson = await res.json();
  153. return resJson;
  154. }